package com.cunfang.interceptor;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.cunfang.util.ConfigUtil;
import com.cunfang.util.RequestResponseContext;
import com.cunfang.util.CONNECTOR;

public class LoginInterceptor extends HandlerInterceptorAdapter {

	private static boolean startTyep = true;
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

				String url = request.getRequestURL().toString();
				RequestResponseContext.setResponse(response);
				RequestResponseContext.setRequest(request);
				
				
				//静态资源不拦截
				if(InitResInfo(url, ConfigUtil.getProperties("sysResFile"))){
					return true;
				}
				//判断是否拦截路径
				if(InitResInfo(url,ConfigUtil.getProperties("IntercerptorUrl"))){
					return true;
				}
				/*//判断是不是登录页面
				String login = request.getHeader("login");
				if("login".equals(login)){
					return true;
				}*/
				/** 验证token **/
				if (CONNECTOR.VERIFYTOKEN(request, response)) {
					return true;
				}
				
				return false;
	}
	
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}
	
	
	
	/**
	 * 判断是否拦截路径
	 * @param url
	 * @param f
	 * @return
	 */
	private boolean InitResInfo(String url, String f) {
		String fval = "";
		for (int i = 0; i < f.split(",").length; i++) {
			fval = f.split(",")[i];
			if (url.indexOf(fval) > -1) {
				return true;
			}
		}
		return false;
	}
	
	
	public boolean isPortUsing(String host, int port)
			throws UnknownHostException {
		boolean flag = false;
		InetAddress theAddress = InetAddress.getByName(host);
		try {
			Socket socket = new Socket(theAddress, port);
			flag = true;
			startTyep = false;
		} catch (IOException e) {

		}
		return flag;
	}
	
	
	

}
